package demo.test;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@RequestMapping("/demo")
@RestController
public class Demo2 {

    //Cookie

    @RequestMapping("/getCookies")
    public String getCookie(HttpServletRequest request, HttpServletResponse response){
        String name = request.getParameter("name");
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            Arrays.stream(cookies).forEach(ck ->
                    System.out.println(ck.getName() + ":" + ck.getValue()));
        }
        return "获取Cookies";
    }

    @RequestMapping("/getCookie")
    public String getCookie(@CookieValue("hello") String hello){
        return "从 Cookie 中获取值：" + hello;
    }


    //Session

    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        session.setAttribute("name","ming");
        return "设置 session 成功";
    }

    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("name");
        return "从 session 中获取：" + name;
    }

    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session){
        String name = (String) session.getAttribute("name");
        return "从 session 中获取：" + name;
    }

    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute("name") String name){
        return "从 session 中获取：" + name;
    }


    //获取 Header
    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request){
        String userAgent = request.getHeader("User-Agent");
        return "从 Header 中获取信息：" + userAgent;
    }

    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent){
        return "从 Header 中获取信息：" + userAgent;
    }

}
